package com.gxa.global.realm;

import com.gxa.mapper.shezhimapper.LoginMapper;
import com.gxa.mapper.shezhimapper.QuanXianMapper;
import com.gxa.mapper.shezhimapper.UserMapper;
import com.gxa.pojo.QuanXian;
import com.gxa.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    LoginMapper loginMapper;

    @Autowired
    UserMapper userMapper;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取用户名
        String username = (String)principalCollection.getPrimaryPrincipal();
        User user = userMapper.selectUser(username);
        if(user!=null)
        {
            int user_id = user.getId();
            List<QuanXian> quanXianList = userMapper.selectAllQuanXian(user_id);
            Set<String>  quanXians = new HashSet<>();
//            List<Integer> quanXians_id = new ArrayList<>();
            if(quanXianList.size()>0)
            {
                for(QuanXian quanXian : quanXianList)
                {
                    quanXians.add(quanXian.getTitle());
//                    quanXians_id.add(quanXian.getId());
                }
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.setStringPermissions(quanXians);
            return info;
        }
        return null;
    }

    //认证 token
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //前端获取的账户
        String username = (String)authenticationToken.getPrincipal();//admin
        //根据前端账户动态查找数据库中的账户信息
        User user = loginMapper.selectUser(username);//sys_user admin cc538a096996a269d18073dd009d3e6f
        if(user != null && user.getPassword() != null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),"myRealm");
            info.setCredentialsSalt(ByteSource.Util.bytes("fzw"));
//            System.out.println(info.getCredentials());
            return info;
        }else{
            return null;
        }
    }

}
